package flinkSql.sink;

import bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;
import org.junit.Test;

import static org.apache.flink.table.api.Expressions.$;

//TODO 流数据实时写入文件中
public class Flink_Sink_File {

    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map((MapFunction<String, SensorReading>) value -> {
                    String[] split = value.split(",");
                    return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                });

        //sql
        tableEnvironment.createTemporaryView("input",input);
        Table inputSql1 = tableEnvironment.sqlQuery("select id,temp from input");


        //DSL
        Table table = tableEnvironment.fromDataStream(input);
        Table inputSql2 = table.select($("id"), $("temp"));

        tableEnvironment.connect(new FileSystem().path("output/tableoutput2"))
                .withFormat(new Csv())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temp", DataTypes.DOUBLE()))
                .createTemporaryTable("output");

        inputSql1.executeInsert("output");
        inputSql2.executeInsert("output");

        env.execute();
    }
}
